package org.setamv.springcloud.resttemplate;

import com.netflix.ribbon.proxy.annotation.Http;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class MyLoadBalancerInterceptor implements ClientHttpRequestInterceptor {

    private static class LoadBalancedHttpRequest implements HttpRequest {
        private HttpRequest sourceRequest;

        public LoadBalancedHttpRequest(HttpRequest sourceRequest) {
            this.sourceRequest = sourceRequest;
        }

        @Override
        public HttpMethod getMethod() {
            return sourceRequest.getMethod();
        }

        @Override
        public URI getURI() {
            URI uri = sourceRequest.getURI();
            String loadBalancedURL = uri.getScheme() + "://" + "www.setamv.tech:9091" + uri.getPath();
            try {
                URI loadBalancedURI = new URI(loadBalancedURL);
                return loadBalancedURI;
            } catch (URISyntaxException e) {
                System.out.println("URI格式错误：" + loadBalancedURL);
                return uri;
            }
        }

        @Override
        public HttpHeaders getHeaders() {
            return sourceRequest.getHeaders();
        }
    }

    /**
     * 下面实现负载均衡的拦截器，负载均衡的实现参见 {@linkplain LoadBalancedHttpRequest}
     * @param request
     * @param body
     * @param execution
     * @return
     * @throws IOException
     */
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        System.out.println("触发拦截器，被拦截的URI=" + request.getURI());
        LoadBalancedHttpRequest convertedRequest = new LoadBalancedHttpRequest(request);
        ClientHttpResponse response = execution.execute(convertedRequest, body);
        return response;
    }
}
